package com.itqf.demo01;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2020/11/20
 * @Time: 上午10:31
 */
public class TestShiro {
    static Logger log = LoggerFactory.getLogger(TestShiro.class);

    public  static  void  main(String[]args) throws  Exception{
        //1.根据shiro.ini创建Factory
        Factory<SecurityManager> factory =
                new IniSecurityManagerFactory("classpath:shiro.ini");

        //2.创建SecurityManager
        SecurityManager securityManager = factory.getInstance();

        //3.设置SecurityManager
        SecurityUtils.setSecurityManager(securityManager);

        //4.构建Subject对象  currentUser
        Subject subject =  SecurityUtils.getSubject();
        if (!subject.isAuthenticated()){//判断是否认证（登录）
            //没有登录过
            UsernamePasswordToken token = new UsernamePasswordToken
                    ("xiaojuan","jbgsn");
            //登录
            try {
                subject.login(token);
            } catch (UnknownAccountException  e) {
              log.error("用户名错误！！");
            }catch(IncorrectCredentialsException e){
                log.error("密码错误！！");
            }

        }else{
            log.info("登录过！！！");
        }

        if (subject.isAuthenticated()){
            log.info("登录成功！！");
        }

        //判断角色
        if (subject.hasRole("test")){
            log.info("xiaojuan具有test角色");
        }

        if (subject.hasRole("admin")){
            log.info("xiaojuan具有admin角色");
        }else{
            log.info("xiaojuan不具有admin角色");
        }
        //权限
        if (subject.isPermitted("app:user:add")){
            log.info("xiaojuan具有新增用户的权限");
        }else{
            log.info("xiaojuan不具有新增用户的权限");
        }

        if (subject.isPermitted("app:user:delete")){
            log.info("xiaojuan具有删除用户的权限");
        }else{
            log.info("xiaojuan不具有删除用户的权限");
        }


    }
}
